package com.study.shengsiyuan.example09;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

import org.junit.Test;
public class _4_NIOTest3 {
	@Test
	public void test1() throws IOException {
		/**input.txt 采用的是 utf-8 编码
		 * input3.txt 采用的是  ISO-8859-1 编码
		 * 	输入输出文件的编码类型不一样 ,  但是 输出文件没有出现乱码
		 */

		String input = "src/main/java/com/shengsiyuan/netty/example08/input.txt";
		String output = "src/main/java/com/shengsiyuan/netty/example08/input3.txt";
		RandomAccessFile in = new  RandomAccessFile(input,"r");
		RandomAccessFile out = new  RandomAccessFile(output,"rw");
		long length = new File(input).length();
		FileChannel fci = in.getChannel();
		FileChannel fco = out.getChannel();
		MappedByteBuffer mbi = fci.map(FileChannel.MapMode.READ_ONLY, 0, length);
		//MappedByteBuffer mbo = fco.map(FileChannel.MapMode.READ_WRITE, 0, length);

		Charset ch =Charset.forName("ISO-8859-1");

		CharsetDecoder cd = ch.newDecoder();
		CharsetEncoder ce = ch.newEncoder();

		CharBuffer  cb = cd.decode(mbi);
		ByteBuffer bb = ce.encode(cb);

		fco.write(bb);
		in.close();
		out.close();

		System.out.println("--------------------------");
		Charset.availableCharsets().forEach((i,v)->{
			System.out.println(i + " , "+ v);
		});

		System.out.println("--------------------------");
	}


}
